package com.GraduationDesign.backend.utils;

import com.GraduationDesign.backend.constant.Constants;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.PullCommand;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.storage.file.FileRepositoryBuilder;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;

import java.io.File;

/**
 * @author DestinyCc
 * @date 2022/4/13
 */
@Slf4j
public class GitUtils {
    public static void clone(String owner, String repo) throws Exception{
        log.info("clone: https://github.com/" + owner + "/" + repo + ".git");
        log.info("use proxy: {}/{}/{}.git", Constants.GITHUB_PROXY, owner, repo);
        UsernamePasswordCredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider("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","");
        Git.cloneRepository()
                .setURI(Constants.GITHUB_PROXY + "/" + owner + "/" + repo + ".git")
                .setDirectory(new File(Constants.DEFAULT_PROJECT_LOCATION + "/" + owner + "/" + repo))
                .setCredentialsProvider(credentialsProvider)
                .call();
    }

    public static void pull(String owner, String repo) throws Exception{
        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        Repository repository = builder.setGitDir(new File(Constants.DEFAULT_PROJECT_LOCATION + "/" + owner + "/"+ repo + "/.git")).readEnvironment()
                .findGitDir() // scan up the file system tree
                .build();
        Git git = new Git(repository);
        UsernamePasswordCredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider("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","");
        PullCommand pull = git.pull().setCredentialsProvider(credentialsProvider);
        pull.call();
    }

}
